import config from './index.js';
import storage from '../utils/Stroage.js'
import store from '../store/index.js'

let requestArr = config.config.requestArr

export const request = (params) =>{
	let headerData= {}
	let baseUrl = ''
	if(!params.isLogin){
		headerData['content-type'] = 'application/json'
		baseUrl = config.config.serviceUrl
	} else {
		headerData['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
		baseUrl = config.config.sysUrl
	}
	let verificationUrl = params.url.substring(0,(params.url.indexOf('.do')+3))	
	return new Promise((resolve, reject) => {
		let url = baseUrl+ params.url;//请求的网络地址和局地的api地址组合
		if(params.OpenLoading === undefined || params.OpenLoading === null || params.OpenLoading === ''){
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}		
		// console.log(requestArr)
		if(requestArr.includes(verificationUrl)){			
			console.log('重复请求，已终止------------------URL:',verificationUrl)
			return false 
		} else {			
			requestArr.push(verificationUrl)
		}
		if(url.indexOf('login') == -1){
			headerData.Authorization = storage.get('token')
		}
		console.log('请求域名',baseUrl)
		console.log(params)
		return uni.request({
			url: url,
			data: params.query === undefined ? {} : params.query,
			method: params.method,
			header: headerData,
			success: (res) => {
				if(res.data.result.length === 1 && (res.data.msg.indexOf('000') == -1)){
					resolve(res.data);
				} else {
					// uni.showToast({
					// 	title:res.data.msg === '' ? `错误码:${res.data.result}` : res.data.msg,
					// 	duration: 3000
					// })
					// 只要token失效就去realoadToken里面去重新加载token
					// 如果缓存下载的加密密码错误，则跳转到login页面
					resolve(res.data);
					if(params.url.indexOf('login') !== -1) return
					store.dispatch('reloadToken')				
				}
				console.log('请求成功res=>',res.data)
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err);
				console.log('请求失败err=>',err)
			},
			complete: () => {
				uni.hideLoading()
				const index = requestArr.indexOf(verificationUrl)
				requestArr.splice(index,1)
				console.log('------------请求结束--------------')
			}
		});
	})
	
	
}